"use server";
import { getPasswordRestTokenByToken } from "@/data/password-reset-token";
import { getUserByEmail } from "@/data/user";
import {
  getVerificationTokenByEmail,
  getVerificationTokenByToken,
} from "@/data/verfication-token";
import { db } from "@/lib/db";
import { v4 as uuidv4 } from "uuid";
import crypto from "crypto";
import { getTwoFactoryTokenByEmail } from "@/data/two-factory-token";
// 生成邮箱登录token
export const generateVerificationToken = async (email: string) => {
  const findToken = await getVerificationTokenByEmail(email);
  if (findToken) {
    await db.verificationToken.delete({
      where: {
        id: findToken.id,
      },
    });
  }
  const token = uuidv4();
  const verificationToken = await db.verificationToken.create({
    data: {
      email,
      token,
      expires: new Date(new Date().getTime() + 3600 * 1000),
    },
  });
  return verificationToken;
};

export const verifyEmail = async (token: string) => {
  const exeistingVerificationToken = await getVerificationTokenByToken(token);
  if (!exeistingVerificationToken) {
    return {
      code: 1,
      data: "Token not found",
    };
  }
  if (new Date().getTime() > exeistingVerificationToken.expires.getTime()) {
    return {
      code: 1,
      data: "Token expired",
    };
  }
  const user = await getUserByEmail(exeistingVerificationToken.email);
  if (!user) {
    return {
      code: 1,
      data: "User not found",
    };
  }
  await db.user.update({
    where: {
      email: exeistingVerificationToken.email,
    },
    data: {
      emailVerified: new Date(new Date().getTime() + 3600 * 1000),
    },
  });
  await db.verificationToken.delete({
    where: {
      id: exeistingVerificationToken.id,
    },
  });
  return {
    code: 0,
    data: "Email verified",
  };
};

// 生成 忘记密码token
export const generateResetPasswordToken = async (email: string) => {
  const findToken = await getPasswordRestTokenByToken(email);
  if (findToken) {
    await db.passwordResetToken.delete({
      where: {
        id: findToken.id,
      },
    });
  }
  const token = uuidv4();
  const verificationToken = await db.passwordResetToken.create({
    data: {
      email,
      token,
      expires: new Date(new Date().getTime() + 3600 * 1000),
    },
  });
  return verificationToken;
};

// 生成双重验证token
export const generateTwoFactoryToken = async (email: string) => {
  const token = crypto.randomInt(100_000, 1_000_000).toString();
  const expires = new Date(new Date().getTime() + 5 * 60 * 1000);
  const existingToken = await getTwoFactoryTokenByEmail(email);
  if (existingToken) {
    await db.twoFactoryToken.delete({
      where: {
        id: existingToken.id,
      },
    });
  }
  const verificationToken = await db.twoFactoryToken.create({
    data: {
      email,
      token,
      expires,
    },
  });
  return verificationToken;
};
